const url = require('url');
const got = require('@/utils/got');
const cheerio = require('cheerio');

const puppeteerGet = (url, cache, waitForSelector) =>
    cache.tryGet(url, async () => {
        const browser = await require('@/utils/puppeteer')();
        const page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', (request) => {
            request.resourceType() === 'document' ? request.continue() : request.abort();
        });
        let html;
        await page.goto(url, {
            waitUntil: 'domcontentloaded',
        });
        await page.waitForSelector('#nocaptcha');
        const nocaptcha = await page.evaluate(() => document.getElementById('nocaptcha').innerHTML);

        console.log('----', nocaptcha)

        await page.waitForSelector('#nc_1_n1t');
        // TODO: 破解滑动验证码
        const sliderElement = await page.$('#nc_1_n1t');
        const slider = await sliderElement.boundingBox();
        const sliderHandle = await page.$('#nc_1_n1z');
        const handle = await sliderHandle.boundingBox();
        await page.mouse.move(handle.x+handle.width/2, handle.y+handle.height/2);
        await page.mouse.down();
        await page.mouse.move(handle.x+slider.width, handle.y+handle.height/2, {step:50});
        await page.mouse.up();

        await page.waitForSelector(waitForSelector).then(async () => {
            html = await page.evaluate(() => document.documentElement.innerHTML);
        });
        await browser.close();
        return html;
    });

module.exports = async (ctx) => {
    const root_url = 'https://sou.zhaopin.com/?jl=566&kw=web%E5%89%8D%E7%AB%AF&p=1';
    const response = await got({
        method: 'get',
        url: root_url,
    });

    let list = [];
    const $ = cheerio.load(response.data);
    const lis = $('div.positionlist>div.joblist-box__item>a');
    for(let i=0; i<lis.length; i++) {
        list.push(lis[i]);
    }

    const count = [];
    for (let i = 0; i < Math.min(list.length, 10); ++i) {
        count.push(i);
    }

    const items = await Promise.all(
        count.map((i) => {
            const item = cheerio.load(list[i])('a');
            const title = item.find('span.iteminfo__line1__jobname__name').first();
            const link = item.attr('href');

            return puppeteerGet(link, ctx.cache, 'div.job-detail').then(html => {
                const content = cheerio.load(html);
                const post = content('div.job-detail>div.describtion');
                const date = content('div.summary-plane__content').find('span.summary-plane__time').text().trim();
                const match = /((\d+)月(\d+)日)/i.exec(date);
                const pubDate = match && new Date(`${new Date().getFullYear()}/${match[2]}/${match[3]} 00:00:00 GMT+8`).toUTCString();

                post.find('img[data-src]').each((_, ele) => {
                    ele = content(ele);
                    ele.attr('src', ele.attr('data-src'));
                    ele.attr('alt', title.attr('title'));
                    ele.attr('title', title.attr('title'));
                    ele.removeAttr('class');
                    ele.removeAttr('data-src');
                });

                return {
                    title: title.attr('title'),
                    link,
                    pubDate,
                    description: post.html(),
                };
            });
        })
    );

    ctx.state.data = {
        title: '智联招聘-唐山',
        link: root_url,
        item: items,
    };
};
